import React, { PureComponent } from 'react';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Row, Col, message, Spin, Tooltip, Form } from 'antd';
import { PrimaryC, SecuritiesCodeC, codeType, CandlestickChartsC, SecondHeaderC, FirstHeaderC } from '../../../../components';
import { connect } from 'dva';
import myStyle from './style.less';
import accounting, { parse } from 'accounting';

let secuChangeSum = 0;
@connect(({ tradeAnalysisNewM, loading }) => ({ tradeAnalysisNewM, loading }))
export default class TradeReplay extends PureComponent {
  constructor(props) {
    super(props);
    this.formRef = React.createRef();

    this.state = {
      KLineData: [], // K线图数据
      indictData: [], // 指标结果
      tradingCode: undefined, // 证券代码
      exchangeCode: undefined, // 交易市场
      firstLoading: true,
      show: true,
      secuDisabled: false, // 证券代码查询按钮的置灰
      showEcharts: false,
      isHaveData: false,
    };
  }

  componentDidMount() {}

  componentDidUpdate(prevProps) {
    if (JSON.stringify(this.props.searchObj) !== JSON.stringify(prevProps.searchObj)) {
      this.securiRef.props.form.resetFields();
      this.setState({
        firstLoading: true,
        show: false,
        secuDisabled: false,
        KLineData: [], // K线图数据
        indictData: [], // 指标结果
        tradingCode: undefined, // 证券代码
        exchangeCode: undefined, // 交易市场
      });
      this.setState({
        show: true,
      });
    }
  }

  componentWillUnmount = () => {
    secuChangeSum = 0;
  };

  secuChange = (e) => {
    secuChangeSum++;
    if (e) {
      this.setState(
        {
          tradingCode: e.tradingCode,
          exchangeCode: e.exchangeCode,
          isHaveData: true,
          showEcharts: true,
        },
        () => {
          if (this.state.firstLoading) {
            this.getReplayData(this.props.searchObj);
          }
        },
      );
    } else {
      this.setState({ isHaveData: false });
    }
  };

  // 获取交易复盘数据
  getReplayData = (searchObj) => {
    if (this.state.tradingCode && this.state.exchangeCode) {
      // 指标结果
      this.props.dispatch({
        type: 'tradeAnalysisNewM/getTradeIndicatorData',
        payload: {
          tradingCode: this.state.tradingCode,
          exchangeCode: this.state.exchangeCode,
          ...searchObj,

          portfolioCodeList: JSON.stringify(searchObj.portfolioCodeList),
        },
        callback: (type, data) => {
          if (type == 'success') {
            this.setState({
              indictData: data,
            });
          }
        },
      });
      // K线图
      this.props.dispatch({
        type: 'tradeAnalysisNewM/getKLineData',
        payload: {
          tradingCode: this.state.tradingCode,
          exchangeCode: this.state.exchangeCode,
          ...searchObj,
          portfolioCodeList: JSON.stringify(searchObj.portfolioCodeList),
        },
        callback: (type, data) => {
          if (type == 'success') {
            this.setState({
              KLineData: data,
            });
          }
        },
      });
    } else {
      if (secuChangeSum == 1 || secuChangeSum == 0) {
        message.warning('该产品下无股票或场内基金持仓');
      } else {
        message.warning('证券代码不能为空！');
      }
    }

    this.setState({ firstLoading: false });
  };

  // 指标结果展示
  showResult = () => {
    const { indictData } = this.state;
    return (
      <Row gutter={16}>
        <Col span={6}>
          <div className={myStyle.resultContain}>
            <div className={myStyle.boxItem}>
              <span>交易次数 :</span>
              <span>{accounting.formatNumber(Number(indictData.TRADE_COUNT))}</span>
            </div>
            <div className={myStyle.boxItem}>
              <span>获利次数 :</span>
              <span>{accounting.formatNumber(Number(indictData.WIN_COUNT))}</span>
            </div>
            <div className={myStyle.boxItem}>
              <span>盈亏金额 :</span>
              <span>{accounting.formatNumber(Number(indictData.ALL_PNL), 2)}</span>
            </div>
          </div>
        </Col>
        <Col span={6}>
          <div className={myStyle.resultContain}>
            <div className={myStyle.boxItem}>
              <span>买入数量 :</span>
              <span>{accounting.formatNumber(Number(indictData.BUY_AMOUNT))}</span>
            </div>
            <div className={myStyle.boxItem}>
              <span>胜率 :</span>
              <span>{accounting.formatNumber(Number(indictData.WIN_RADIO), 2)}</span>
            </div>
            <div className={myStyle.boxItem}>
              <span>做多盈亏 :</span>
              <span>{accounting.formatNumber(Number(indictData.LONG_PNL), 2)}</span>
            </div>
          </div>
        </Col>
        <Col span={6}>
          <div className={myStyle.resultContain}>
            <div className={myStyle.boxItem}>
              <span>卖出数量 :</span>
              <span>{accounting.formatNumber(Number(indictData.SELL_AMOUNT))}</span>
            </div>
            <div className={myStyle.boxItem}>
              <span>做多次数 :</span>
              <span>{accounting.formatNumber(Number(indictData.LONG_COUNT))}</span>
            </div>
            <div className={myStyle.boxItem}>
              <span>做空盈亏 :</span>
              <span>{accounting.formatNumber(Number(indictData.SHORT_PNL), 2)}</span>
            </div>
          </div>
        </Col>
        <Col span={6}>
          <div className={myStyle.resultContain}>
            <div className={myStyle.boxItem}>
              <span>净买入数量 :</span>
              <span>{accounting.formatNumber(Number(indictData.NET_BUY_AMOUNT))}</span>
            </div>
            <div className={myStyle.boxItem}>
              <span>做空次数 :</span>
              <span>{accounting.formatNumber(Number(indictData.SHORT_COUNT))}</span>
            </div>
            <div className={myStyle.boxItem}>
              <span>平均持仓时间 :</span>
              <span>{accounting.formatNumber(Number(indictData.AVG_HOLD_TIME), 2)}</span>
            </div>
          </div>
        </Col>
      </Row>
    );
  };

  // 证券代码查询事件
  onQueryCode = () => {
    console.log('rtrt', this.securiRef);
    if (this.securiRef.props.form.getFieldsValue().securityCode) {
      this.getReplayData(this.props.searchObj);
    } else {
      if (secuChangeSum == 1 || secuChangeSum == 0) {
        message.warning('该产品下无股票或场内基金持仓');
      } else {
        message.warning('证券代码不能为空！');
      }
    }
  };

  render() {
    const { loading } = this.props;
    return (
      <>
        <FirstHeaderC
          title='交易复盘'
          Left={
            <Tooltip title='针对股票和场内基金'>
              <QuestionCircleOutlined style={{ paddingLeft: '7px' }} />
            </Tooltip>
          }
          arrowBtn={!this.state.isHaveData}
          showContent={this.state.showEcharts}
          onExpendClick={(e) => {
            this.setState({ showEcharts: e });
          }}
        />
        <div style={{ height: '100%', display: this.state.showEcharts ? 'block' : 'none' }}>
          {this.state.show && (
            <>
              <div style={{ marginBottom: '10px' }}>
                <Form ref={this.formRef}>
                  <Row>
                    <Col span={6}>
                      {/* {this.state.show && */}
                      <SecuritiesCodeC
                        form={this.formRef.current}
                        dataIndex='securityCode'
                        codeType={codeType.inPortfolio}
                        queryItems={{
                          productCode: this.props.searchObj.portfolioCodeList.join(','),
                          securityType: '1,9,101,201,109,209',
                          beginDate: this.props.secuBeginDate,
                          endDate: this.props.secuEndDate,
                        }}
                        isInitFirstData={true}
                        allowClear={true}
                        onRef={(ref) => (this.securiRef = ref)}
                        onChange={this.secuChange}
                      />
                      {/* } */}
                    </Col>
                    <div>
                      <PrimaryC style={{ float: 'left', margin: '0 10px' }} title={'查询'} onClick={this.onQueryCode} disabled={this.state.secuDisabled} />
                    </div>
                  </Row>
                </Form>
              </div>
              <div style={{ marginBottom: '10px' }}>
                <SecondHeaderC title='交易K线图' />
                <Spin spinning={loading.effects['tradeAnalysisNewM/getKLineData'] == true}>
                  <CandlestickChartsC height={400} data={this.state.KLineData} />
                </Spin>
              </div>
              <div style={{ marginBottom: '10px' }}>
                <SecondHeaderC title='指标结果' />
                <Spin spinning={loading.effects['tradeAnalysisNewM/getTradeIndicatorData'] == true}>{this.showResult()}</Spin>
              </div>
            </>
          )}
        </div>
      </>
    );
  }
}
